package project.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import schronisko.MySQLConnection;
import utils.Email_Password;

/**
 * Servlet implementation class PasswordReminder
 */
@WebServlet("/PasswordReminder")
public class PasswordReminder extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PasswordReminder() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {


		String email = request.getParameter("email");
		String url = request.getRequestURL().toString();
		String url2 = url.substring(0,url.length()-16)+"index.jsp";
		HttpSession s = request.getSession();
		if (email.equals("")){
			s.setAttribute("remind", 3);
			response.sendRedirect("PasswordReminder.jsp");
		}
		

		else if (passwordreminder(email, url2) == 1) {

			s.setAttribute("remind", 1);
			

			response.sendRedirect("PasswordReminder.jsp");
		} else {

			s.setAttribute("remind", 2);
			response.sendRedirect("PasswordReminder.jsp");
		}

	}

	public static int passwordreminder(String email, String url) {
		int rows = 0;
		try {  
			char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
			StringBuilder sb = new StringBuilder();
			Random random = new Random();
			for (int i = 0; i < 10; i++) {
			    char c = chars[random.nextInt(chars.length)];
			    sb.append(c);
			}
			
			String temp_password = sb.toString();
			
			rows = MySQLConnection.connect().executeUpdate("UPDATE login_data SET password= '" + temp_password + "' WHERE email = '"+email+"'");
			Email_Password.SendPasswordMail(email, temp_password,url);
			MySQLConnection.Close();
			return rows;
		} catch (SQLException e) {
			
		} catch (Exception exception) {
			
		}
		return rows;
	}
}
